package com.vlin.automation.actuator;

import org.json.JSONObject;

import com.vlin.entity.scene.Automation;
import com.vlin.scene.actuator.SceneActuator;

public abstract class AbstractAutomationActuator implements AutomationActuator {

	//专有的消息接收器
	
	//消息发送器
	/*
	 * ExecutorService executorService = new ThreadPoolExecutor(2, 2, 0,
	 * TimeUnit.SECONDS, new ArrayBlockingQueue<>(512), new
	 * ThreadPoolExecutor.DiscardPolicy());
	 */
	
	private SceneActuator sceneActuator;
	
	private ConditionReceiver conditionReceiver;
	
	private ListConditionSender listConditionSender;
	
	
	@Override
	public void start(Automation automation) {
		if(automation != null && getListConditionSender() != null) {
			
			for(String condition : automation.getConditions()) {
				try {
					getListConditionSender().sendToStart(automation.getId(), new JSONObject(condition), automation);
				}catch (Exception e) {
					
				}
			}
		}
	}

	@Override
	public void stop(Automation automation) {
		//关闭某个条件过滤
		if(automation != null && getListConditionSender() != null) {
			for(String condition : automation.getConditions()) {
				try {
					getListConditionSender().sendToEnd(automation.getId(), new JSONObject(condition), automation);
				}catch (Exception e) {
					
				}
			}
		}
	}
	
	//接收所有条件成功的，使用队列，并执行动作
	@Override
	public void accept() {
		do {
			Automation automation = getConditionReceiver().getAutomation();
			
			if(automation != null) {
				getSceneActuator().execute(automation);
			}
		} while(true);
		
	}

	@Override
	public void setSceneActuator(SceneActuator sceneActuator) {
		if(sceneActuator != null)
			this.sceneActuator = sceneActuator;
		
	}

	@Override
	public SceneActuator getSceneActuator() {
		
		return this.sceneActuator;
	}

	@Override
	public void setConditionReceiver(ConditionReceiver conditionReceiver) {
		if(conditionReceiver != null) {
			this.conditionReceiver = conditionReceiver;
		}
		
	}

	@Override
	public ConditionReceiver getConditionReceiver() {
		
		return this.conditionReceiver;
	}

	@Override
	public void setListConditionSender(ListConditionSender listConditionSender) {
		if(listConditionSender != null) {
			this.listConditionSender = listConditionSender;
		}
		
	}

	@Override
	public ListConditionSender getListConditionSender() {
		
		return this.listConditionSender;
	}
	

}
